import time

import cv2
import numpy as np
import pyautogui

import logo.Mlog
from match import photo
from match.photo import Match


# //截屏
def take_screenshot():
    # 截取屏幕截图
    screenshot = pyautogui.screenshot()
    screenshot_np = np.array(screenshot)
    screenshot_bgr = cv2.cvtColor(screenshot_np, cv2.COLOR_RGB2BGR)
    return resize_and_crop_image(screenshot_bgr, 0, 5)


reduce_height = None


def resize_and_crop_image(image, width_reduction=0, height_reduction=0):
    height, width = image.shape[:2]
    global reduce_height
    # 计算减少的像素
    reduce_width = int(width * width_reduction / 100)
    reduce_height = int(height * height_reduction / 100)
    # 新的宽度和高度
    new_width = width - 2 * reduce_width
    new_height = height - 2 * reduce_height

    # 确保新宽度和高度都大于0
    if new_width <= 0 or new_height <= 0:
        raise ValueError("Reduction percentage is too high, resulting in non-positive dimensions.")

    # 裁剪图像
    cropped_image = image[reduce_height:reduce_height + new_height, reduce_width:reduce_width + new_width]

    return cropped_image

def move_mouse(start_x, start_y, distance, direction='right', duration=0.5):
    """
    从指定的起始位置移动鼠标到某个方向的一定距离。

    :param start_x: 起始位置的x坐标
    :param start_y: 起始位置的y坐标
    :param distance: 移动的距离（以像素为单位）
    :param direction: 移动的方向（'right', 'left', 'up', 'down'）
    :param duration: 移动的持续时间（秒）
    """
    # 计算目标位置
    if direction == 'right':
        end_x = start_x + distance
        end_y = start_y
    elif direction == 'left':
        end_x = start_x - distance
        end_y = start_y
    elif direction == 'up':
        end_x = start_x
        end_y = start_y - distance
    elif direction == 'down':
        end_x = start_x
        end_y = start_y + distance
    else:
        raise ValueError("Invalid direction. Use 'right', 'left', 'up', or 'down'.")
    pyautogui.mouseDown(start_x,start_y)
    # 移动鼠标
    pyautogui.moveTo(end_x, end_y, duration=duration)
    # 松开鼠标
    pyautogui.mouseUp()
def is_black_screen(image, threshold=10):
    # 计算图像的平均亮度
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    average_brightness = np.mean(gray_image)
    # 判断平均亮度是否低于某个阈值
    return average_brightness < threshold


# 默认n=1是单机=0是双击
def click_icons(match: Match, n: int = 1):
    # print("name=", match.name)
    # print("center_x, center_y=", match.center_x, match.center_y)
    # 转换为屏幕坐标系
    # screen_x = match.center_x + pyautogui.size().width // 2
    # screen_y = match.center_y + pyautogui.size().height // 2
    # print("screen_x, screen_y=", screen_x, screen_y)
    # 点击图标
    # pyautogui.click(screen_x, screen_y)
    # pyautogui.doubleClick(match.center_x, match.center_y)
    try:
        if n:
            pyautogui.click(match.center_x, match.center_y + reduce_height)
        else:
            pyautogui.doubleClick(match.center_x, match.center_y + reduce_height)
            print(f"点击击操作成功: ({match.center_x}, {match.center_y+reduce_height})")
        # pydirectinput.click(match.center_x, match.center_y)
        # print(f"点击击操作成功: ({match.center_x}, {match.center_y})")
    except Exception as e:
        print(f"双击操作失败: {e}")
    print(f"点击ICO图标，名字:{match.name} 位置：({match.center_x}, {match.center_y+reduce_height})")
    # 等待一小段时间
    pyautogui.sleep(0.1)  # 可以根据需要调整等待时间


pass


def click_icons_pot(x: float, y: float, n: int = 1):
    try:
        if n:
            pyautogui.click(x, y+reduce_height)
        else:
            pyautogui.doubleClick(x, y+reduce_height)
        # pydirectinput.click(match.center_x, match.center_y)
        print(f"点击击操作成功: ({x}, {y+reduce_height})")
    except Exception as e:
        print(f"双击操作失败: {e}")
    # print(f"点击ICO图标，名字:{match.name} 位置：({match.center_x}, {match.center_y})")
    # try:
    #     # pyautogui.click(match.center_x, match.center_y)
    #     pydirectinput.click(x, y)
    #     print(f"双击操作成功: ({x}, {y})")
    #     pyautogui.sleep(0.5)  # 可以根据需要调整等待时间
    # except Exception as e:
    #     print(f"双击操作失败: {e}")
    #     # print(f"点击ICO图标，名字:{match.name} 位置：({match.center_x}, {match.center_y})")
    #     # 等待一小段时间


def click_icon(path: str, n: int = 0):
    shot = take_screenshot()
    print("shot=", shot)
    matchs, shot = photo.find_icons_semblance_screenshot(shot, path)

    match = matchs[0]
    print("name=", match.name)
    print("center_x, center_y=", match.center_x, match.center_y)
    # 转换为屏幕坐标系
    # screen_x = match.center_x + pyautogui.size().width // 2
    # screen_y = match.center_y + pyautogui.size().height // 2
    # print("screen_x, screen_y=", screen_x, screen_y)
    # 点击图标
    # pyautogui.click(screen_x, screen_y)
    # pyautogui.doubleClick(match.center_x, match.center_y)
    try:
        if n:
            pyautogui.click(match.center_x, match.center_y)
        else:
            pyautogui.doubleClick(match.center_x, match.center_y)
        # pydirectinput.click(match.center_x, match.center_y)
        print(f"点击击操作成功: ({match.center_x}, {match.center_y})")
    except Exception as e:
        print(f"双击操作失败: {e}")
    print(f"点击ICO图标，名字:{match.name} 位置：({match.center_x}, {match.center_y})")
    # 等待一小段时间
    pyautogui.sleep(0.1)  # 可以根据需要调整等待时间


pass


def mouse_hold(x, y, duration: float = 0.1):
    try:
        # 按下鼠标左键
        pyautogui.mouseDown(x=x, y=y, button='left')
        time.sleep(duration)
        pyautogui.mouseUp(x=x, y=y, button='left')
    except pyautogui.FailSafeException:
        print("Fail-safe triggered! Mouse moved to a screen corner.")


# 持续按下键盘按键一秒钟的函数
def press_key_for_duration(key, duration, max_retries=3):
    retries = 0
    while retries < max_retries:
        try:
            # logger.info(f"Pressing key {key} for {duration} seconds. Attempt {retries + 1}/{max_retries}")
            pyautogui.keyDown(key)
            time.sleep(duration)
            pyautogui.keyUp(key)
            return  # Exit the function if successful
        except pyautogui.FailSafeException:
            # logger.error("Fail-safe triggered. Mouse moved to a corner of the screen.")
            retries += 1
            time.sleep(0.2)  # Optional: Wait before retrying
    logo.Mlog.logger.error(f"Failed to press key {key} after {max_retries} attempts.")
    # logger.error(f"Failed to press key {key} after {max_retries} attempts.")
    # Optionally raise an exception or handle the failure scenario here


def press_key_in_background(key, duration):
    try:
        pyautogui.keyDown(key)
        time.sleep(duration)
        pyautogui.keyUp(key)
    except pyautogui.FailSafeException:
        logo.Mlog.logger.error("Fail-safe triggered. Mouse moved to a corner of the screen.")


if __name__ == "__main__":
    while True:
        mouse_hold(100, 100, 5)
